﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Weibo4Sharp.Service;
using System.Configuration;
using System.Diagnostics;
using Weibo4Sharp.Model;

namespace Weibo4SharpWeb.Controllers
{
    public abstract class WeiboControllerBase : Controller
    {
        public static string ConsumerKey { get; private set;}
        public static string ConsumerSecret { get; private set; }

        protected RedirectResult NewHomeResult()
        {
            return new RedirectResult("/");
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Trace.TraceInformation("OnActionExecuting " + this);
            
            if (Session["weibo_user"] != null)
            {
                ViewBag.WeiboUser = (WeiboUser)Session["weibo_user"];
            }
            else
            {
                if (!(this is OAuthController))
                {
                    var host = Request.ServerVariables["HTTP_HOST"];
                    var returnUrl = string.Format("http://{0}{1}", host, Request.RawUrl);
                    filterContext.Result = new RedirectResult("/OAuth/Authorize?returnUrl=" + returnUrl);
                    return;
                }
            }

            base.OnActionExecuting(filterContext);
        }

        static WeiboControllerBase()
        {
            ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
            ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];
        }

        public WeiboService GetService()
        {
            var service = new WeiboService(ConsumerKey, ConsumerSecret);

            return service;
        }

        public WeiboService GetAuthenticatedService()
        {
            var accessToken = (OAuthAccessToken)Session["access_token"] ?? null;            

            if(accessToken == null ) 
            {
                return null;
            }

            var service = new WeiboService(ConsumerKey, ConsumerSecret);
            service.AuthenticateWith(accessToken.Token.ToString(), accessToken.TokenSecret.ToString());
            return service;
        }

    }
}
